<?php
class Transaction extends AppModel {
    var $validate = array(
        'unit_code_id' => array(
            'valid' => array(
                'rule' => 'vUnit',
                'message' => 'Wajib diisi dengan Unit Kerja yang ada'
            )
        ),
        'activity_id' => array(
            'valid' => array(
                'rule' => 'vActivity',
                'message' => 'Wajib diisi dengan Sub Kegiatan yang ada'
            )
        ),
        'transaction_date' => array(
            'valid' => array(
                'required' => true,
                'allowEmpty' => false,
                'rule' => 'date',
                'message' => 'Wajib diisi dengan tanggal'
            )
        ),
        'cash_receipt_no' => array(
            'valid' => array(
                'rule' => 'vCashReceiptNo',
                'message' => 'Diisi dengan No seperti 001 atau biarkan kosong'
            )
        ),
        'cash_receipt_no_in' => array(
            'valid' => array(
                'rule' => 'vCashReceiptNoIn',
                'message' => 'Diisi dengan No seperti 001 atau biarkan kosong'
            )
        ),
        'amount_out' => array(
            'valid' => array(
                'rule' => 'vAmount',
                'message' => 'Isi pengeluaran atau penerimaan, tidak boleh kosong keduanya'
            )
        ),
        'amount_in' => array(
            'valid' => array(
                'rule' => 'vAmount',
                'message' => 'Isi pengeluaran atau penerimaan, tidak boleh kosong keduanya'
            )
        )
    );
    
    var $hasMany = array(
        'TransactionRevision',
        'JournalCash' => array(
            'dependent' => true
        ),
    );
    
    var $hasOne = array(
        'JournalBank' => array(
            'dependent' => true
        ),
        'JournalTax' => array(
            'dependent' => true
        )
    );
    
    var $belongsTo = array(
        'UnitCode', 'Activity', 'ActivityChild',
        'CashReceiver',
        'User' => array(
            'foreignKey' => 'created_by'
        )
    );
    
    function beforeSave() {
        // get last cash_receipt_counter
        // on current month only if
        // cash_receipt_no and cash_receipt_no_in is
        // empty and is not a transaction from/to bank
        if ( (empty($this->data[$this->alias]['cash_receipt_no']) &&
              empty($this->data[$this->alias]['cash_receipt_no_in'])) &&
             (empty($this->data[$this->alias]['sp2d_no']) &&
              empty($this->data[$this->alias]['check_no'])) ) {
        
            $date = explode('-', $this->data[$this->alias]['transaction_date']);
            $y = $date[0];
            $m = $date[1];
            $lastNoIn = 0;
            $lastNoOut = 0;
            $type = 'cash_receipt_no';
            
            // jika no. kas untuk pengeluaran
            if ( $this->data[$this->alias]['amount_out'] ) {
                $a = $this->find('first', array(
                    'conditions' => array(
                        $this->alias . '.transaction_date >=' => $y . '-' . $m . '-01',
                        $this->alias . '.transaction_date <=' => $y . '-' . $m . '-31'
                    ),
                    'fields' => array('cash_receipt_no'),
                    'order' =>  $this->alias . '.cash_receipt_no DESC',
                    'recursive' => -1
                ));
                
                if ( !empty($a) ) {
                    $lastNoOut = $a[$this->alias]['cash_receipt_no'] ?
                        $a[$this->alias]['cash_receipt_no'] : 0;
                }
            } else { // berarti no. kas untuk penerimaan
                $a = $this->find('first', array(
                    'conditions' => array(
                        $this->alias . '.transaction_date >=' => $y . '-' . $m . '-01',
                        $this->alias . '.transaction_date <=' => $y . '-' . $m . '-31'
                    ),
                    'fields' => array('cash_receipt_no_in'),
                    'order' =>  $this->alias . '.cash_receipt_no_in DESC',
                    'recursive' => -1
                ));
                $type = 'cash_receipt_no_in';
                
                if ( !empty($a) ) {
                    $lastNoIn = $a[$this->alias]['cash_receipt_no_in'] ?
                        $a[$this->alias]['cash_receipt_no_in'] : 0;
                }
            }
            $lastNo = $lastNoOut;
            if ( $lastNoIn > $lastNoOut ) {
                $lastNo = $lastNoIn;
            }
            
            $no = str_pad(($lastNo + 1), 5, '0', STR_PAD_LEFT);
            $this->data[$this->alias][$type] = $no;
        
        } else {
            if ( $this->data[$this->alias]['cash_receipt_no'] == '-' ||
                    $this->data[$this->alias]['cash_receipt_no'] == '0' ) {
                $this->data[$this->alias]['cash_receipt_no'] = '-';
            }
            
            if ( $this->data[$this->alias]['cash_receipt_no_in'] == '-' ||
                    $this->data[$this->alias]['cash_receipt_no_in'] == '0' ) {
                $this->data[$this->alias]['cash_receipt_no_in'] = '-';
            }
        }
        
        return true;
    }
    
    function afterSave($created) {
        // save to transaction_revisions
        // and related journal
        
        // first save to transaction_revisions
        $TransactionRevision = $this->data['Transaction'];
        
        // get latest revision of current transaction_date
        // and save it to transaction_revisions
        $a = $this->TransactionRevision->find('first', array(
            'conditions' => array(
                'TransactionRevision.transaction_date' => $TransactionRevision['transaction_date']
            ),
            'fields' => array('revision_no', 'created'),
            'order' => 'revision_no DESC',
            'recursive' => -1
        ));
        $lastRev = 0;
        if ( !empty($a) ) {
            $lastRev = $a['TransactionRevision']['revision_no'] ? $a['TransactionRevision']['revision_no'] : 0;
        }
        
        if ( isset($a['TransactionRevision']['created']) && 
            $a['TransactionRevision']['created'] == $TransactionRevision['created'] ) {
            $rev = $lastRev;
        } else {    
            $rev = $lastRev+1;
        }
        
        $TransactionRevision['revision_no'] = $rev;
        $TransactionRevision['transaction_id'] = $this->id;
        $this->TransactionRevision->create();
        $this->TransactionRevision->save($TransactionRevision);
        
        $JournalBank = array();
        $JournalBank['transaction_id'] = $this->id;
        $JournalBank['transaction_date'] = $TransactionRevision['transaction_date'];
        $JournalBank['check_no'] = $TransactionRevision['check_no'];
        $JournalBank['sp2d_no'] = $TransactionRevision['sp2d_no'];
        $JournalBank['debit_amount'] = $TransactionRevision['amount_in'] ? $TransactionRevision['total'] : 0;
        $JournalBank['credit_amount'] = $TransactionRevision['amount_out'] ? $TransactionRevision['total'] : 0;
        $JournalCash['reduction'] = $TransactionRevision['reduction'] ? $TransactionRevision['reduction'] : 0;
        $JournalBank['description'] = $TransactionRevision['description'];
        $JournalBank['created'] = $TransactionRevision['created'];
        
        $JournalCash = array();
        $JournalCash['transaction_id'] = $this->id;
        $JournalCash['transaction_date'] = $TransactionRevision['transaction_date'];
        $JournalCash['cash_receipt_no'] = $TransactionRevision['cash_receipt_no'];
        $JournalCash['cash_receipt_no_in'] = $TransactionRevision['cash_receipt_no_in'];
        $JournalCash['debit_amount'] = $TransactionRevision['amount_in'] ? $TransactionRevision['total'] : 0;
        $JournalCash['credit_amount'] = $TransactionRevision['amount_out'] ? $TransactionRevision['total'] : 0;
        $JournalCash['tax_code'] = '';
        $JournalCash['description'] = $TransactionRevision['description'];
        $JournalCash['created'] = $TransactionRevision['created'];
        
        // now save to journal
        // based on amount_in or amount_out
        // and based how it flows from (wether bank or cash)
        if ( $TransactionRevision['amount_out'] ) {
            // our checking cash/bank for out now depends
            // on wether check_no or cash_receipt_no is set
            if ( !empty( $TransactionRevision['check_no']) ) {
                // this is out from bank
                $this->JournalBank->create();
                $this->JournalBank->save($JournalBank);
                
                // since this is out from bank
                // we need to insert to cash also
                
                // since credit amount is received to cash
                // we need to alter debit_amount cash
                $JournalCash['debit_amount'] = $TransactionRevision['amount_out'];
                $JournalCash['credit_amount'] = 0;
                $JournalCash['description'] = 'Ambil uang dari bank<br />Cek ' . 
                    $TransactionRevision['check_no'];
                $this->JournalCash->create();
                $this->JournalCash->save($JournalCash);
                
            } else if ( !empty( $TransactionRevision['cash_receipt_no']) ) {
                // also save to journal tax
                // and journal cash as amount_in
                // ONLY when tax_code is set,
                // see set tax code in __saving() on controller
                if ( isset( $TransactionRevision['tax_code'] ) && $TransactionRevision['tax_code'] ) {
                    // save to journal tax
                    $JournalTax = array();
                    $JournalTax['transaction_date'] = $TransactionRevision['transaction_date'];
                    $JournalTax['transaction_id'] = $TransactionRevision['transaction_id'];
                    $JournalTax['accounting_no'] = $TransactionRevision['mak_code'] . '/' .
                        $TransactionRevision['cash_receipt_no'];
                    $JournalTax['description'] = $TransactionRevision['tax_description'];
                    $JournalTax['tax_ppndn'] = $TransactionRevision['tax_ppndn'];
                    $JournalTax['tax_pph21'] = $TransactionRevision['tax_pph21'];
                    $JournalTax['tax_pph22'] = $TransactionRevision['tax_pph22'];
                    $JournalTax['tax_pph23'] = $TransactionRevision['tax_pph23'];
                    $JournalTax['tax_other'] = $TransactionRevision['tax_other'];
                    $JournalTax['total'] = $TransactionRevision['tax_amount'];
                    $JournalTax['created'] = $TransactionRevision['created'];
                    $this->JournalTax->create();
                    $this->JournalTax->save($JournalTax);
                    
                    // alter Journal Cash as amount_in
                    // for applied tax
                    $JournalCashIn['transaction_id'] = $this->id;
                    $JournalCashIn['transaction_date'] = $TransactionRevision['transaction_date'];
                    $JournalCashIn['cash_receipt_no'] = '';
                    $JournalCashIn['cash_receipt_no_in'] = $TransactionRevision['cash_receipt_no'];
                    $JournalCashIn['debit_amount'] = 0;
                    $JournalCashIn['credit_amount'] = 0;
                    $JournalCashIn['tax_code'] = '';
                    $JournalCashIn['description'] = '';
                    $JournalCashIn['created'] = $TransactionRevision['created'];
                    
                    if ( $TransactionRevision['tax_ppndn'] ) {
                        $JournalCashIn['debit_amount'] = $TransactionRevision['tax_ppndn'];
                        $JournalCashIn['tax_code'] = 'PPN-DN';
                        $JournalCashIn['description'] = 'Diterima PPN-DN';
                        $this->__saveJournalCashForTax($JournalCashIn);
                    }
                    if ( $TransactionRevision['tax_pph21'] ) {
                        $JournalCashIn['debit_amount'] = $TransactionRevision['tax_pph21'];
                        $JournalCashIn['tax_code'] = 'PPH-21';
                        $JournalCashIn['description'] = 'Diterima PPH-21';
                        $this->__saveJournalCashForTax($JournalCashIn);
                    }
                    if ( $TransactionRevision['tax_pph22'] ) {
                        $JournalCashIn['debit_amount'] = $TransactionRevision['tax_pph22'];
                        $JournalCashIn['tax_code'] = 'PPH-22';
                        $JournalCashIn['description'] = 'Diterima PPH-22';
                        $this->__saveJournalCashForTax($JournalCashIn);
                    }
                    if ( $TransactionRevision['tax_pph23'] ) {
                        $JournalCashIn['debit_amount'] = $TransactionRevision['tax_pph23'];
                        $JournalCashIn['tax_code'] = 'PPH-23';
                        $JournalCashIn['description'] = 'Diterima PPH-23';
                        $this->__saveJournalCashForTax($JournalCashIn);
                    }
                    if ( $TransactionRevision['tax_other'] ) {
                        $JournalCashIn['debit_amount'] = $TransactionRevision['tax_other'];
                        $JournalCashIn['tax_other'] = 'LAIN-LAIN';
                        $JournalCashIn['description'] = 'Diterima LAIN-LAIN';
                        $this->__saveJournalCashForTax($JournalCashIn);
                    }
                }
                
                // this is out from cash
                $this->JournalCash->create();
                $this->JournalCash->save($JournalCash);
            }
        } else if ( $TransactionRevision['amount_in'] ) {
            if ( !empty( $TransactionRevision['sp2d_no']) ) {
                // this is in to bank
                $this->JournalBank->create();
                $this->JournalBank->save($JournalBank);
                
            } else if ( !empty( $TransactionRevision['cash_receipt_no_in']) ) {
                // this is in to cash
                $this->JournalCash->create();
                $this->JournalCash->save($JournalCash);
            }    
        }
    }
    
    function __saveJournalCashForTax($data) {
        // this is in to cash
        $this->JournalCash->create();
        $this->JournalCash->save($data);
    }
/**
 * Realizations per year from all units
 */
    function getRealizations($year, $specific = null) {
        $conditions = array(
            $this->alias . '.transaction_date >=' =>  $year . '-01-01',
            $this->alias . '.transaction_date <=' =>  $year . '-12-31',
        );
        
        if ( $specific == 'pudir2' ) {
            $conditions[$this->alias.'.unit_code_id'] = array(2,3,4);
        }
        
        $this->Behaviors->attach('Containable');
        $t = $this->find('all', array(
            'conditions' => $conditions,
            'contain' => array(),
            'fields' => array(
                $this->alias . '.amount_in', $this->alias . '.amount_out',
                $this->alias . '.total', $this->alias . '.activity_id',
                $this->alias . '.unit_code_id'
            )
        ));
        $ret = array();
        foreach ($t as $_kt => $_t) {
            if ( $_t[$this->alias]['amount_out']*1 && $_t[$this->alias]['activity_id'] ) {
                if ( !isset($ret[$_t[$this->alias]['unit_code_id']]
                    [$_t[$this->alias]['activity_id']]) ) {
                    
                    $ret[$_t[$this->alias]['unit_code_id']]
                        [$_t[$this->alias]['activity_id']] = 0;
                }
                $ret[$_t[$this->alias]['unit_code_id']]
                    [$_t[$this->alias]['activity_id']] += $_t[$this->alias]['total'];
            }
        }
        
        return $ret;
    }

/**
 * Specific realizations for particular unit
 * and per year based
 */
    function getRealization($unit_code_id, $year) {
        $this->Behaviors->attach('Containable');
        $t = $this->find('all', array(
            'conditions' => array(
                $this->alias . '.transaction_date >=' =>  $year . '-01-01',
                $this->alias . '.transaction_date <=' =>  $year . '-12-31',
                $this->alias . '.unit_code_id' => $unit_code_id
            ),
            'contain' => array(),
            'fields' => array(
                $this->alias . '.amount_in', $this->alias . '.amount_out',
                $this->alias . '.total', $this->alias . '.activity_id'
            )
        ));
        $ret = array();
        foreach ($t as $_kt => $_t) {
            if ( $_t[$this->alias]['amount_out']*1 && $_t[$this->alias]['activity_id'] ) {
                if ( !isset($ret[$_t[$this->alias]['activity_id']]) ) {
                    $ret[$_t[$this->alias]['activity_id']] = 0;
                }
                $ret[$_t[$this->alias]['activity_id']] += $_t[$this->alias]['total'];
            }
        }
        
        return $ret;
    }

/**
 * Get realization based on type of source_fund
 * (bind, unbind, and pnbp)
 * @param mixed $year year of transaction
 * @return array $r
 */
    function getCompositionRealizations($year) {
        $conditions = array(
            $this->alias . '.transaction_date >=' =>  $year . '-01-01',
            $this->alias . '.transaction_date <=' =>  $year . '-12-31',
        );
        
        $this->Behaviors->attach('Containable');
        $this->ActivityChild->bindModel(array(
            'hasMany' => array('BudgetDetail' => array(
                'className' => 'BudgetDetail'
            ))
        ));
        $this->ActivityChild->BudgetDetail->Behaviors->attach('Containable');
        $t = $this->find('all', array(
            'conditions' => $conditions,
            'contain' => array(),
            'fields' => array(
                $this->alias . '.amount_in', $this->alias . '.amount_out',
                $this->alias . '.total', $this->alias . '.activity_id',
                $this->alias . '.activity_child_id', $this->alias . '.unit_code_id'
            )
        ));
        
        $fund_sources = array(
            'bind' => 0, 'unbind' => 0, 'pnbp' => 0
        );
        foreach ($t as $_kt => $_t) {
            if ( $_t[$this->alias]['amount_out']*1 && $_t[$this->alias]['activity_id'] ) {
                // check fund source
                if ( $_t[$this->alias]['activity_child_id'] ) {
                        
                    $_fs = $this->ActivityChild->BudgetDetail->find('first', array(
                        'conditions' => array(
                            'BudgetDetail.activity_child_id' => $_t[$this->alias]['activity_child_id'],
                            'Budget.unit_code_id' => $_t[$this->alias]['unit_code_id'], 
                            'Budget.activity_id' => $_t[$this->alias]['activity_id'] 
                        ),
                        'contain' => array(
                            'BudgetDetailDescription' => array(
                                'fields' => 'BudgetDetailDescription.fund_source'
                            ),
                            'Budget'
                        ),
                        'fields' => array('BudgetDetail.id'),
                    ));
                    
                    if (isset($fund_sources[
                            $_fs['BudgetDetailDescription'][0]['fund_source']
                        ])) {
                            
                        $fund_sources[
                            $_fs['BudgetDetailDescription'][0]['fund_source']
                        ] += $_t[$this->alias]['total'];
                    }
                    
                    
                }
            }
        }
        
        return $fund_sources;
    }
/**
 * get realizations group by MAK
 */
    function getRealizationMAK($year) {
        $conditions = array(
            $this->alias . '.transaction_date >=' =>  $year . '-01-01',
            $this->alias . '.transaction_date <=' =>  $year . '-12-31',
            $this->alias . '.activity_id <>' => null,
            $this->alias . '.activity_child_id <>' => null
        );
        
        $this->Behaviors->attach('Containable');
        $t = $this->find('all', array(
            'conditions' => $conditions,
            'contain' => array('ActivityChild'),
            'fields' => array(
                $this->alias . '.cash_receipt_no',
                $this->alias . '.amount_out',
                $this->alias . '.activity_id',
                $this->alias . '.total',
                $this->alias . '.transaction_date',
                'ActivityChild.code'
            )
        ));
        
        $ret = array();
        
        // group activity with activity_child as its childs
        // there are activity_child with empty activity's parent
        // TODO: tell project owner
        foreach ($t as $_kt => $_t) {
            if ( $_t[$this->alias]['amount_out']*1 && $_t['ActivityChild']['code'] ) {
                if ( !isset($ret[$_t[$this->alias]['activity_id']][$_t['ActivityChild']['code']]) ) {
                    $ret[$_t[$this->alias]['activity_id']][$_t['ActivityChild']['code']] = array('total' => 0, 'cash_receipt_no' => $_t[$this->alias]['cash_receipt_no'], 'transaction_date' => $_t[$this->alias]['transaction_date']);
                    //$ret[$_t[$this->alias]['activity_id']][$_t['ActivityChild']['code']] = 0;
                }
                $ret[$_t[$this->alias]['activity_id']][$_t['ActivityChild']['code']]['total'] += $_t[$this->alias]['total'];
            }
        }
        
        return $ret;
    }

/**
 * Called by cpdprinthtml on budgets_controller
 */
    function getRealizationMAKForComposition($year) {
        $conditions = array(
            $this->alias . '.transaction_date >=' =>  $year . '-01-01',
            $this->alias . '.transaction_date <=' =>  $year . '-12-31',
            $this->alias . '.activity_id <>' => null,
            $this->alias . '.activity_child_id <>' => null
        );
        
        $this->Behaviors->attach('Containable');
        $t = $this->find('all', array(
            'conditions' => $conditions,
            'contain' => array('ActivityChild'),
            'fields' => array(
                $this->alias . '.amount_out',
                $this->alias . '.activity_id',
                $this->alias . '.total',
                'ActivityChild.code'
            )
        ));
        
        $ret = array();
        
        // group activity with activity_child as its childs
        // there are activity_child with empty activity's parent
        // TODO: tell project owner
        foreach ($t as $_kt => $_t) {
            if ( $_t[$this->alias]['amount_out']*1 && $_t['ActivityChild']['code'] ) {
    
                if ( !isset($ret[$_t['ActivityChild']['code']]) ) {
                    $ret[$_t['ActivityChild']['code']] = 0;
                }
                $ret[$_t['ActivityChild']['code']] += $_t[$this->alias]['total'];
            }
        }
        
        return $ret;
    }
    
    function vUnit($field) {
        if ( isset($field["unit_code_id"]) && !empty($field["unit_code_id"]) ) {
            return $this->UnitCode->find('count', array(
                'conditions' => array(
                    'UnitCode.id' => $field["unit_code_id"]
                ),
                'recursive' => -1
            )) > 0;
        }
        
        return true;
    }
    
    function vActivity($field) {
        if ( isset($field['activity_id']) && !empty($field['activity_id']) ) {
            return $this->Activity->find('count', array(
                'conditions' => array(
                    'Activity.id' => $field['activity_id']
                ),
                'recursive' => -1
            )) > 0;
        }
        
        return true;
    }
    
    function vCashReceiptNo($field) {
        // exception for '-' and 0
        if ( $field['cash_receipt_no'] == '-' || $field['cash_receipt_no'] == '0' ) {
            return true;
        }
        
        if ( isset($field['cash_receipt_no']) && !empty($field['cash_receipt_no']) ) {
            return preg_match('/^[0-9]{1,5}$/', $field['cash_receipt_no']);
        }
        
        return true;
    }
    
    function vCashReceiptNoIn($field) {
        // exception for '-' and 0
        if ( $field['cash_receipt_no_in'] == '-' || $field['cash_receipt_no_in'] == '0' ) {
            return true;
        }
        
        if ( isset($field['cash_receipt_no_in']) && !empty($field['cash_receipt_no_in']) ) {
            return preg_match('/^[0-9]{1,5}$/', $field['cash_receipt_no_in']);
        }
        
        return true;
    }
    
    function vAmount() {
        if (empty($this->data[$this->alias]['amount_in']) && empty($this->data[$this->alias]['amount_out'])) {
            return false;
        }
        
        return true;
    }
    
    function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
        $this->Behaviors->attach('Containable');
        $fields = array(
            'id', 'activity_id', 'unit_code_id', 
            'transaction_date', 'sp2d_no', 'check_no',
            'cash_receipt_no',
            'cash_receipt_no_in',
            'amount_in', 'amount_out', 'spj',
            'total', 'created_by', 'created'
        );
        $contain = array(
            'User' => array(
                'fields' => array('name')
            ),
            'UnitCode' => array(
                'fields' => array('name')
            ),
            'Activity' => array(
                'fields' => array('name', 'code')
            )
        );
        $order = $this->alias . '.transaction_date ASC';
        $records = $this->find('all', compact(
            'conditions', 'fields', 'order', 'limit', 
            'page', 'recursive', 'group', 'contain'
            )
        );
        
        foreach ($records as $key => $record) {
            $records[$key][$this->alias]['amount_out'] = number_format(
                $records[$key][$this->alias]['amount_out'],2,'.',',');
            $records[$key][$this->alias]['amount_in'] = number_format(
                $records[$key][$this->alias]['amount_in'],2,'.',',');
            $records[$key][$this->alias]['total'] = number_format(
                $records[$key][$this->alias]['total'],2,'.',',');
        }
        
        return $records;
    }
    
    function getTotal($month = null, $year = null) {
        if ( is_null($month) ) {
            $month = date('m');
        }
        
        
        if ( is_null($year) ) {
            $year = date('Y');
        }
        
        $this->Behaviors->attach('Containable');
        $records = $this->find('all', array(
            'conditions' => array(
                //'Transaction.transaction_date >=' => $year . '-' . $m . '-01',
                //'Transaction.transaction_date <=' => $year . '-' . $m . '-31'
                'Transaction.transaction_date <' => $year . '-' . $month . '-01'
            ),
            //'order' => 'Transaction.transaction_date ASC, Transaction.id ASC',
            'order' => 'Transaction.transaction_date ASC, Transaction.cash_receipt_no ASC',
            'contain' => array(
                'JournalBank' => array(
                    'order' => 'JournalBank.transaction_date ASC, JournalBank.transaction_id ASC'
                ),
                'JournalCash' => array(
                    'order' => 'JournalCash.transaction_date ASC, JournalCash.transaction_id ASC'
                ),
                'Activity' => array(
                    'fields' => array('Activity.code')
                ),
                'ActivityChild' => array(
                    'fields' => array('ActivityChild.code')
                )
            )
        ));
        
        $tIn = $tOut = 0;
        foreach ($records as $r) {
            if ( !empty($r['JournalBank']) ) {
                $r['JournalBank']['debit_amount'] = $r['JournalBank']['debit_amount']*1;
                $r['JournalBank']['credit_amount'] = $r['JournalBank']['credit_amount']*1;
                if ( $r['JournalBank']['debit_amount'] ) {
                    $tIn += $r['JournalBank']['debit_amount'];
                } else if ( $r['JournalBank']['credit_amount'] ) {
                    $tOut += $r['JournalBank']['credit_amount'];
                }
            }
            
            
            if ( !empty($r['JournalCash']) ) {
                foreach ( $r['JournalCash'] as $r_ ) {
                    $r_['debit_amount'] = $r_['debit_amount']*1;
                    $r_['credit_amount'] = $r['Transaction']['amount_out']*1;
                    if ( $r_['debit_amount'] ) {
                        $tIn += $r_['debit_amount'];
                    } else if ( $r_['credit_amount'] ) {
                        $tOut += $r_['credit_amount'];
                    }
                }
            }
        }
        
        /*
        $tBank = $this->JournalBank->getTotal($month, $year);
        $tCash = $this->JournalCash->getTotal($month, $year);
        $ret = ($tBank['total_debit']+$tCash['total_debit']) -
            ($tBank['total_credit']+$tCash['total_credit']);*/
        
        
        return ($tIn-$tOut);
    }
}
?>
